from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
import os
import console_lobby
import shutil
import subprocess
import datetime
class WidgetGallery(QtGui.QDialog):
    def NetWorkStatus(self):
        
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        startupinfo.wShowWindow = subprocess.SW_HIDE

        ipPipe = subprocess.Popen(('ping',"192.168.1.11" ), stdout=subprocess.PIPE, startupinfo = startupinfo)
        ipStr = ipPipe.stdout.read()
        if 'Reply' in ipStr:
            return True
        else:
            return False

    def __init__(self, parent=None):
    
        QtGui.QWidget.__init__(self, parent)        
        
        settings = QSettings("LobbyRecord", "Borqs") # Use the Borqs Magic seetings
        
        #Create the oputput label ,edit ,and button.
        self.outputwidget = {}
        self.outputwidget['label']  = QtGui.QLabel("Output")
        self.outputwidget['edit']   = QtGui.QLineEdit()
        self.outputwidget['edit'].setMinimumWidth(240)
        self.outputwidget['button'] = QtGui.QPushButton('...')              
        self.outputwidget['button'].setMaximumWidth (25)
        
        #Create the input label ,edit ,and button.
        self.inputwidget = {}
        self.inputwidget['label']  = QtGui.QLabel("Input")
        self.inputwidget['edit']   = QtGui.QLineEdit()
        self.inputwidget['edit'].setMinimumWidth(240)
        self.inputwidget['button'] = QtGui.QPushButton('...')              
        self.inputwidget['button'].setMaximumWidth (25) 

        topLayout = QtGui.QHBoxLayout()     
        for x in ('label', 'edit', 'button'):
                topLayout.addWidget(self.inputwidget[x])
                
        bottomLayout = QtGui.QHBoxLayout()     
        for x in ('label', 'edit', 'button'):
                bottomLayout.addWidget(self.outputwidget[x])
                
        self.ExeButton = self.createButton(self.tr("Execute"),self.ExeClicked)
        self.ExitButton = self.createButton(self.tr("Exit"),self.ExitClicked)
        self.ReloadButton = self.createButton(self.tr("Reload"),self.ReloadClicked)


        self.connect(self.inputwidget['button'], SIGNAL("clicked()"), self.InputClicked)
        self.connect(self.outputwidget['button'], SIGNAL("clicked()"), self.OutputClicked)

        buttonLayout = QtGui.QHBoxLayout()
        buttonLayout.addStretch(1)
        buttonLayout.addWidget(self.ReloadButton)
        buttonLayout.addWidget(self.ExeButton)
        buttonLayout.addWidget(self.ExitButton)

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addLayout(topLayout)
        mainLayout.addLayout(bottomLayout)
        mainLayout.addLayout(buttonLayout)
        
        self.setLayout(mainLayout)
        self.setWindowTitle(self.tr("Lobby 0.9.0"))
        self.ReloadClicked()
        
    def ExeClicked(self):
        """Exe test command"""
        argv = []
        argv.append('-i')        
        inputfile = unicode((self.inputwidget['edit'].text() ))
        outputfile = unicode(str(self.outputwidget['edit'].text() ))
        argv.append(inputfile)
        argv.append('-o')        
        argv.append(outputfile)
        console_lobby.main(*argv)
        
        seetings = QSettings('LobbyRecord', 'Borqs')
        seetings.setValue('output dir', QVariant(outputfile))
        seetings.setValue('input dir', QVariant(inputfile))    
        
        if os.path.exists(self.outputwidget['edit'].text()):
            QtGui.QMessageBox.information(self,"Success","Your xls have been created.......")
            if self.NetWorkStatus() == True:
                dt = datetime.datetime.now()
                filename = dt.strftime("%Y-%m-%d-%H-%M-%S.xls")
                shutil.copy(str(self.outputwidget['edit'].text()),'\\\\192.168.1.11\\share\\usr\\b090\\lobby\\%s'%(filename))
            
        else:
            QtGui.QMessageBox.information(self,"Fail","Your xls have not been created!!!!!!")


    def OutputClicked(self):
        seetings = QSettings('LobbyRecord', 'Borqs')
        if seetings.contains('output dir'):            
            fileName = unicode(QtGui.QFileDialog.getSaveFileName(self, self.tr("Save xls File"), QVariant(seetings.value('output dir')).toString(),
                                                     self.tr("xls Files(*.xls);;")))
        else:
            fileName = unicode(QtGui.QFileDialog.getSaveFileName(self, self.tr("Save xls File"), '',
                                                     self.tr("xls Files(*.xls);;")))    
        if  fileName:
            self.outputwidget['edit'].setText(fileName)

    def InputClicked(self):
        seetings = QSettings('LobbyRecord', 'Borqs')
        if seetings.contains('input dir'):            
            fileName = unicode(QtGui.QFileDialog.getOpenFileName(self, self.tr("Save xls File"), QVariant(seetings.value('input dir')).toString(),
                                                     self.tr("xls Files(*.xls);;")))
        else:
            fileName = unicode(QtGui.QFileDialog.getOpenFileName(self, self.tr("Save xls File"), '',
                                                     self.tr("xls Files(*.xls);;")))    
        if  fileName:
            self.inputwidget['edit'].setText(fileName)

            
    def ExitClicked(self):
        self.close()
    def createButton(self, text, member):
        button = QtGui.QPushButton(text)
        self.connect(button, QtCore.SIGNAL("clicked()"), member)
        return button    
    def ReloadClicked(self):        
        """"""
        settings = QSettings('LobbyRecord', 'Borqs')

        self.outputwidget['edit'].setText(QVariant(settings.value('output dir')).toString())       
        self.inputwidget['edit'].setText(QVariant(settings.value('input dir')).toString())                                             
   
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)        
    gallery = WidgetGallery()
    gallery.show()
    sys.exit(app.exec_()) 
